import 'package:flutter/material.dart';
import '../../model/movie.dart';

class MoiveDataSource extends DataTableSource {

  final List<Movie> _movies = movies;
  int _selectedRowCount = 0;

  @override
  int get rowCount => _movies.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => _selectedRowCount;

  @override
  DataRow getRow(int index) {
    final Movie _movie = _movies[index];

    return DataRow.byIndex(
      index: index,
      cells: [
        DataCell(Text(_movie.title)),
        DataCell(Text(_movie.author)),
      ]);
  }

  void _sort(getField(moive), bool ascending) {
    _movies.sort((a, b) {
      if (!ascending) {
        final c = a;
        a = b;
        b = c;
      }

      final aValue = getField(a);
      final bValue = getField(b);

      return Comparable.compare(aValue, bValue);
    });

    notifyListeners();
  }
}

class PaginationDataTableDemo extends StatefulWidget {
  PaginationDataTableDemo({Key key}) : super(key: key);

  @override
  _PaginationDataTableDemoState createState() => _PaginationDataTableDemoState();
}

class _PaginationDataTableDemoState extends State<PaginationDataTableDemo> {
  int _sortColumnIndex = 0;
  bool _sortAscending = true;

  final MoiveDataSource _moivesDataSource = MoiveDataSource();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("PaginationDataTableDemo"),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: ListView(
          children: [
            PaginatedDataTable(
              header: Text("Moives"),
              rowsPerPage: 5, // 每页显示条数，默认显示 10 行
              source: _moivesDataSource,
              sortColumnIndex: _sortColumnIndex, // 表格排序的列的索引
              sortAscending: _sortAscending, // true 表示升序排列
              // onSelectAll: (bool value) { }, // 修改全选的状态
              columns: [
                DataColumn(
                  label: Text("电视剧"),
                  onSort: (int columnIndex, bool ascending) {
                    // 排序
                    _moivesDataSource._sort(
                      (movie) => movie.title.length,
                      ascending
                    );

                    setState(() {
                      _sortColumnIndex = columnIndex;
                      _sortAscending = ascending;
                    });

                  }
                ),
                DataColumn(label: Text("作者")),
              ], 
            ),
          ],
        ),
      ),
    );
  }
}